<template>
    <div class="ry-image-base64-container">
        <input ref="getFile" type="file" accept=".png,.jpg,.jpeg,image/png,image/jpeg" @change="changeFile">
        <button type="button" @click="copyBase64">复制Base64</button>
    </div>
    <div class="fy-image-base64-div">
        {{ imageToBase64 }}
    </div>
</template>

<script setup lang="ts" name="ImageBase64Conversion">
import { useTemplateRef, ref } from 'vue'
const file = useTemplateRef("getFile")
const imageToBase64 = ref<string | ArrayBuffer>('')
const changeFile = () => {
    if (file.value) {
        const files = file.value.files
        console.log(files, "2");
        if (files && files.length) {
            const f = files[0]
            console.log(f, "change");
            const canvas = document.createElement("canvas")
            let base64: any = null;
            const reader = new FileReader()
            reader.onload = (e) => {
                imageToBase64.value = e.target?.result || ''
                console.log("读取");

            }
            reader.onerror = (e) => {
                imageToBase64.value = "解析异常"
            }
            reader.readAsDataURL(files[0]);
        }
    }


}
const copyBase64 = () => {
    if(imageToBase64.value){
        navigator.clipboard.writeText(imageToBase64.value as string).then(() => {
            alert("复制成功")
        }).catch(() => {
            alert("复制失败")
        })
    }
}


</script>

<style lang="scss" scoped>
.ry-image-base64-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
}

.fy-image-base64-div {
    border: 1px solid #00000038;
    border-radius: 4px;
    padding: 4px;
    word-break: break-all;
    height: 450px;
    width: calc(100% - 20px);
    overflow: hidden;
    overflow-y: auto;
}
</style>